<?php
class PhpPhantApplication
{
    static private $PhpPhantInstance;
    private $conn;
    private $manager;
    private $dbh;
    private $system;
    public static function autoLoad($className)
    {
        $paths = array(CORE_PATH, LIB_PATH, MODULE_PATH,HELPERS_PATH);
        foreach($paths as $path)
        {
            if( is_dir( $path ) ) {
                $dir = opendir( $path );
                while( false !== $item = readdir( $dir ) ) {
                    $current = $path . "/$item";
                    if( is_dir( $current ) ) {
                        $file = self::checkFileExists( $current, $className );
                        if( $file ) {
                            include_once $file;
                            return;
                        }
                    }
                    else
                    {
                        if($item == $className)
                        {
                            include_once $current;
                            return;
                        }
                    }
                }
            }
        }
        throw new Exception( "$className does not exists" );
    }
    private static function checkFileExists( $dir_name, $filename )
    {
	$file = $dir_name . "/$filename.php";
	return file_exists( $file ) ? $file : false;
    }
    private function  __construct($bootstrap) {
        require_once($bootstrap);
        define('MODULE_PATH', $system['module_path']);
        define('MODEL_PATH', $system['model_path']);
        define('TEMPLATE_PATH', $system['template_path']);
        define('CORE_PATH', $system['core_path']);
        define('LIB_PATH', $system['lib_path']);
        define('HELPERS_PATH', $system['helpers']);
        $this->system = $system;
        require_once($this->system["lib_path"] . DIRECTORY_SEPARATOR .
                'Doctrine.php');
        spl_autoload_register(array('Doctrine', 'autoload'));
        require_once $this->system["lib_path"] . DIRECTORY_SEPARATOR .
                        'Dwoo' . DIRECTORY_SEPARATOR . 'dwooAutoload.php';
        spl_autoload_register("PhpPhantApplication::autoLoad");
        $this->manager = Doctrine_Manager::getInstance();
        $this->dbh = new PDO($db['dsn'], $db['userDb'], $db['passDb']);
        $this->manager->setAttribute(Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES, true);
        $this->manager->setAttribute(Doctrine_Core:: ATTR_AUTO_ACCESSOR_OVERRIDE, true);
    }
    public function generateModels()
    {
        $this->conn = Doctrine_Manager::connection($this->dbh);
        $this->conn->setAttribute(Doctrine_Core::ATTR_VALIDATE,
                Doctrine_Core::VALIDATE_ALL);
        $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true);
        $this->conn->setAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE, false);
        //Allow autoload classes
        $this->manager->setAttribute(Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES, true);
        //Allow accessor overriding
        $this->manager->setAttribute(Doctrine_Core:: ATTR_AUTO_ACCESSOR_OVERRIDE, true);
        Doctrine_Core:: generateModelsFromDb($this->system['model_path'], 
                array('conn'), array('generateTableClasses' => true));
        $this->manager->closeConnection($this->conn);
    }
    public function run()
    {
        $this->conn = Doctrine_Manager::connection($this->dbh);
        $this->conn->setAttribute(Doctrine_Core::ATTR_VALIDATE, Doctrine_Core::VALIDATE_ALL);
        $this->conn->setAttribute(Doctrine_Core::ATTR_QUOTE_IDENTIFIER, true);
        $this->conn->setAttribute(Doctrine_Core::ATTR_HYDRATE_OVERWRITE, true);
        Doctrine_Core::loadModels($this->system["model_path"].'/generated');
        Doctrine_Core::loadModels($this->system["model_path"]);
        $this->manager->openConnection($this->dbh);
        $module = isset($_POST['module'])
            ? $_POST['module']
            : (isset($_GET['module']) ? $_GET['module'] : "");
        if(!empty($module))
            $module = new $module;
        else
          $module = new $this->system['default_module'];
        if(!$module instanceof Module)
              throw new Exception('Nothing to do.');
        else
        {
            $config = Core::getInstance($this->system);
            $module->setConfigInstance($config);
        }
        $action = isset($_POST['action'])
            ? $_POST['action']
            : (isset($_GET['action']) ? $_GET['action'] : "");
        if(!empty($action))
        {
            if(method_exists( $module, $action))
                $module->$action();
            else
                throw new Exception('Nothing to do.');
        }
        else
          $module->index();
        $this->manager->closeConnection($this->conn);
    }
    static public function getInstance($bootstrap)
    {
        if(self::$PhpPhantInstance == null)
        {
           self::$PhpPhantInstance = new self($bootstrap);
        }
        return self::$PhpPhantInstance;
    }
}
?>